<?php

namespace services\common;

use Yii;
use common\models\member\Member;
use common\models\rbac\Role;
use common\models\rbac\UserRole;
use common\models\common\Log;
use common\helpers\CommonHelper;
use common\components\Service;
use common\models\common\ActionLog;
use common\helpers\ArrayHelper;
use Zhuzhichao\IpLocationZh\Ip;

/**
 * Class ActionLogService
 * @package services\sys
 */
class ActionLogService extends Service
{
    /**
     * @param $app_id
     * @param $user_id
     * @param int $limit
     * @return array|\yii\db\ActiveRecord[]
     */
    public function findByAppIdAndManagerId($app_id, $user_id, $limit = 12)
    {
        return ActionLog::find()
            ->where(['app_id' => $app_id, 'user_id' => $user_id, 'status' => 1])
            ->andWhere(['in', 'behavior', ['login', 'logout']])
            ->limit($limit)
            ->orderBy('id desc')
            ->asArray()
            ->all();
    }

    /**
     * 行为日志
     *
     * @param $behavior
     * @param $remark
     * @param bool $noRecordData
     * @param string $url
     * @return bool
     * @throws \yii\base\InvalidConfigException
     */
//    public function create($behavior, $remark, $noRecordData = true, $url = '')
//    {
//        empty($url) && $url = CommonHelper::getUrl();
//
//        $ip = Yii::$app->request->userIP;
//        $model = new ActionLog();
//        $model->behavior = $behavior;
//        $model->remark = $remark;
//        $model->user_id = Yii::$app->user->id ?? 0;
//        $model->url = $url;
//        $model->app_id = Yii::$app->id;
//        $model->get_data = Yii::$app->request->get();
//        $model->post_data = $noRecordData == true ? Yii::$app->request->post() : [];
//        // $model->post_data = $noRecordData == true ? file_get_contents("php://input") : [];
//        $model->header_data = ArrayHelper::toArray(Yii::$app->request->headers);
//        $model->method = Yii::$app->request->method;
//        $model->module = Yii::$app->controller->module->id;
//        $model->controller = Yii::$app->controller->id;
//        $model->action = Yii::$app->controller->action->id;
//        $model->device = CommonHelper::detectVersion();
//        $model->ip = $ip;
//        $model->ip = (string) $model->ip;
//        // ip转地区
//        if (!empty($ip) && ($ipData = Ip::find($ip))) {
//            $model->country = $ipData[0];
//            $model->provinces = $ipData[1];
//            $model->city = $ipData[2];
//        }
//
//        $model->save();
//    }

    public function createLog($response, $noRecordData = true, $url = '')
    {
        empty($url) && $url = CommonHelper::getUrl();

        if ('excel' == Yii::$app->controller->id) {
            return true;
        }

        $member = Yii::$app->user->identity->member_id ?? '';

        $content = '';

        if ($member) {
            $memberModel = Member::findOne($member);
        } elseif ($url == '/v1/site/login') {
            $memberModel = Member::find()
                ->where([
                    'mobile' => Yii::$app->request->post('mobile'),
                    'status' => Member::STATUS_ENABLE
                ])->one();
            $content = '登录系统';
            $module = '登录';
        }

        $member_id = $memberModel->id ?? 0;
        $realname = $memberModel->realname ?? '';

        // 获取用户角色
        $roleArray = UserRole::find()
            ->select('r.name')
            ->alias('u')
            ->leftJoin(Role::tableName() . ' r', 'r.id = u.role_id')
            ->where(['u.member_id' => $member_id])
            ->column();

        if (!empty($roleArray)) {
            $role = implode(',', $roleArray);
        }

        $serialArray = Log::find()
            ->select(['serial_no'])
            ->orderBy(['serial_no' => SORT_DESC])
            ->limit(1)
            ->column();

        $serial_no = $serialArray[0] ?? 0;

        $ip = Yii::$app->request->userIP;
        $model = new Log();
        $model->user_id = $member_id;
        $model->realname = $realname;
        $model->role = $role ?? '';
        $model->url = $url;
        $model->app_id = Yii::$app->id;
        $model->get_data = Yii::$app->request->get();
        $model->post_data = $noRecordData == true ? Yii::$app->request->post() : [];
        $model->header_data = ArrayHelper::toArray(Yii::$app->request->headers);
        $model->project_id = Yii::$app->request->headers->get('ProjectId', 0);
        $model->method = Yii::$app->request->method;
        $model->module =$module ?? Yii::$app->controller->module->id;
        $model->controller = Yii::$app->controller->id;
        $model->action = Yii::$app->controller->action->id;
        $model->device = CommonHelper::detectVersion();
        $model->system = CommonHelper::get_os();
        $model->terminal = CommonHelper::get_bro();
        $model->serial_no = $serial_no + 1;
        $model->content = $content;
        $model->ip = $ip;
        $model->ip = (string) $model->ip;
        $model->ip .= ' | ' . CommonService::getIpLocation($model->ip);
        $model->error_code = $response['code'];
        $model->error_msg =  $response['message'];
        $model->error_data = $response['code'] != 200 ? $response['data'] : '';
        $model->status =  $response['code'] = 200 ? Log::STATUS_NORMAL : Log::STATUS_ABNORMAL;
        $model->created_at = time();
        $model->updated_at = time();

        $model->save();
    }

    /**
     * @api {post} ADDRESS
     * @apiName 日志列表
     * @apiGroup
     * @apiParam {Number}
     * @apiParam {String}
     * @author loujie
     * @param $params
     * @param int $page
     * @param int $pageSize
     * @return array
     * @throws \yii\mongodb\Exception
     */
    public function getList($params, $page = 1, $pageSize = 20)
    {
        $query = Log::find()
            ->select(['user_id', 'realname', 'role', 'serial_no', 'ip', 'system', 'terminal', 'content', 'created_at', 'url', 'error_code', 'module']);
//            ->where(['project_id' => $params['project_id']]);

        isset($params['user_id']) && !empty($params['user_id']) && $query->andWhere(['user_id' => $params['user_id']]);
        isset($params['realname']) && !empty($params['realname']) && $query->andWhere(['like', 'realname', $params['realname']]);
        isset($params['content']) && !empty($params['content']) && $query->andWhere(['like', 'content', $params['content']]);

        if (!empty($params['start_time']) && !empty($params['end_time'])) {
            $query->andWhere(['between', 'created_at', strtotime($params['start_time']) ,strtotime($params['end_time'] . " 23:59:59")]);
        }

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $data = $query
            ->orderBy(['created_at' => SORT_DESC])
            ->asArray()
            ->all();

        foreach ($data as &$item) {
            $array = json_decode(json_encode($item["_id"]),true);
            $item['oid'] = $array['$oid'];
            $item['result'] = $item['error_code'] == 200 ? '成功' : '失败';
            $item['created_at'] = date('Y-m-d H:i:s', $item['created_at']);
        }

        return [
            'total' =>$total,
            'list' => $data,
            'page' => $page,
            'pageSize' => $pageSize
        ];
    }

    /**
     * @apiName 日志详情
     * @apiGroup
     * @apiParam {Number}
     * @apiParam {String}
     * @author loujie
     * @param $id
     * @return array|\yii\mongodb\ActiveRecord|null
     */
    public function getDetail($id)
    {
        $detail = Log::find()
            ->where(['_id' => $id])
            ->asArray()
            ->one();

        if (!$detail) {
            return CommonHelper::api('402','该日志不存在');
        }
        $detail['created_at'] = date('Y-m-d H:i:s', $detail['created_at']);

        return $detail;
    }

}